package com.ququ.syb.mqhandler.service;

import com.ququ.common.utils.OkHttpClientUtil;
import com.ququ.syb.common.constant.RabbitMqQueueNameConstant;
import com.ququ.syb.common.constant.RedisKeyConstant;
import com.ququ.syb.common.pojo.WithdrawCallbackLog;
import com.ququ.syb.common.pojo.WithdrawOrder;
import com.ququ.syb.mqhandler.fegin.WithdrawOrderFegin;
import com.ququ.syb.mqhandler.mongodb.WithdrawCallbackLogDao;
import com.ququ.syb.mqhandler.rabbitmq.RabbitMQSender;
import com.ququ.syb.mqhandler.redis.RedisDao;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WithdrawNotifyService {

    private Logger logger = LoggerFactory.getLogger(WithdrawNotifyService.class);
    @Autowired
    private WithdrawOrderFegin withdrawOrderFegin;
    @Autowired
    private RedisDao redisDao;
    @Autowired
    private RabbitMQSender rabbitMQSender;
    @Autowired
    private WithdrawCallbackLogDao withdrawCallbackLogDao;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public void notifyWithdraw(String tradenum) {
        WithdrawOrder withdrawOrder = withdrawOrderFegin.queryWithdrawOrder(tradenum).getData();
        if (withdrawOrder == null) {
            logger.error("{}提现订单不存在", tradenum);
            return;
        }
        if (StringUtils.isBlank(withdrawOrder.getCallbackurl())) {
            logger.error("{}提现订单没有异步回调通知地址，无法完成回调",tradenum);
            return;
        }
        Jedis jedis = redisDao.getJedis();
        try {
            if (jedis.incr(RedisKeyConstant.WITHDRAWAL_NOTIFY_COUNT + tradenum) > 10) {
                logger.error("{}提现订单已经回调通知超过10次，停止回调",tradenum);
                return;
            }
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("outorderno", withdrawOrder.getOutordernum());
            param.put("tradenum", withdrawOrder.getPaytradenum() != null ? withdrawOrder.getPaytradenum() : withdrawOrder.getTradenum());
            param.put("status", withdrawOrder.getStatus());   //正常单返回订单的自身状态
            param.put("bankaccountname", withdrawOrder.getBankaccountname());
            param.put("costcommission", withdrawOrder.getCommission());
            param.put("customercommission", withdrawOrder.getCustomercommission());
            param.put("bankname", withdrawOrder.getBankname());
            param.put("amount", withdrawOrder.getAmount());
            logger.debug("{}提现订单异步回调参数:{}", tradenum, param);
            WithdrawCallbackLog withdrawCallbackLog = new WithdrawCallbackLog();
            withdrawCallbackLog.setTradenum(tradenum);
            withdrawCallbackLog.setTime(simpleDateFormat.format(new Date()));
            withdrawCallbackLog.setCallbackUrl(withdrawOrder.getCallbackurl());
            withdrawCallbackLog.setParams(param);
            withdrawCallbackLog = withdrawCallbackLogDao.save(withdrawCallbackLog);
            String result = OkHttpClientUtil.post(withdrawOrder.getCallbackurl(), param, null);
            logger.debug("{}提现订单异步通知返回结果:{}", tradenum, result);
            withdrawCallbackLog.setResponse(result);
            withdrawCallbackLogDao.save(withdrawCallbackLog);
            rabbitMQSender.send(RabbitMqQueueNameConstant.DEAD_NOTIFY_WITHDRAWAL, tradenum, 10 * 60 * 1000L);
        }catch (Exception e){
            logger.error("提现订单异步通知应用时异常",e);
            rabbitMQSender.send(RabbitMqQueueNameConstant.DEAD_NOTIFY_WITHDRAWAL, tradenum, 10 * 60 * 1000L);
        }finally {
            redisDao.close(jedis);
        }
    }
}
